using Acme.BookStore.Car;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Acme.BookStore.Car
{
    public class StockInOrderAppService : CrudAppService<
        OrderStockIn, StockInOrderDto, int, PagedAndSortedResultRequestDto, CreateUpdateStockInOrderDto>, IStockInOrderAppService
    {
        public StockInOrderAppService(IRepository<OrderStockIn, int> repository) : base(repository)
        {
        }

        // 1. 批量添加主表+明细
        public async Task<StockInOrderDtoWithDetails> CreateWithDetailsAsync(CreateUpdateStockInOrderDto input)
        {
            var stockInOrder = ObjectMapper.Map<CreateUpdateStockInOrderDto, OrderStockIn>(input);
            stockInOrder = await Repository.InsertAsync(stockInOrder, autoSave: true);
            var detailDtos = new List<StockInOrderDetailDto>();
            if (input.Details != null && input.Details.Count > 0)
            {
                foreach (var detailDto in input.Details)
                {
                    var detail = ObjectMapper.Map<CreateUpdateStockInOrderDetailDto, OrderDetailInt>(detailDto);
                    detail.IntOrderId = stockInOrder.Id;
                    await LazyServiceProvider.LazyGetRequiredService<IRepository<OrderDetailInt, int>>().InsertAsync(detail);
                    var detailResult = ObjectMapper.Map<OrderDetailInt, StockInOrderDetailDto>(detail);
                    detailDtos.Add(detailResult);
                }
            }
            var stockInOrderDto = ObjectMapper.Map<OrderStockIn, StockInOrderDto>(stockInOrder);
            return new StockInOrderDtoWithDetails
            {
                StockInOrder = stockInOrderDto,
                Details = detailDtos
            };
        }

        // 2. 根据调拨单生成入库单及明细（不直接保存，返回前端编辑）
        public async Task<StockInOrderDtoWithDetails> CreateFromInventoryTransferAsync(int inventoryTransferId)
        {
            var transfer = await LazyServiceProvider.LazyGetRequiredService<IRepository<InventryTran, int>>().GetAsync(inventoryTransferId);
            if (transfer == null)
                throw new Volo.Abp.UserFriendlyException("调拨单不存在");
            var transferDetails = await LazyServiceProvider.LazyGetRequiredService<IRepository<Merchandise, int>>().GetListAsync(x => x.InventoryTranId == inventoryTransferId);
            var stockInOrder = new StockInOrderDto
            {
                Id = transfer.Id,
                InventoryTranId = transfer.Id,
                InventoryTransferType = transfer.InventoryTransferType,
                InventoryTransferNo = transfer.InventoryTransferNo,
                InventoryTransferInt = transfer.InventoryTransferOUT, // 注意字段名对应
                IntDateTime = System.DateTime.Now,
                InventoryTransferOperator = transfer.InventoryTransferOperator,
                Remarks = transfer.Remarks,
                OrderNoint = "RK" + System.DateTime.Now.ToString("yyyyMMddHHmmssfff")
            };
            var stockInOrderDetails = transferDetails.Select(d => new StockInOrderDetailDto
            {
                Id = d.Id,
                IntOrderId = null,
                MerchandiseId = d.GoodsId,
                MerchandiseNo = d.MerchandiseNo,
                MerchandiseName = d.MerchandiseName,
                MerchandiseType = d.MerchandiseType,
                MerchandiseModel = d.MerchandiseModel,
                MerchandiseUnit = d.MerchandiseUnit,
                MerchandiseOut = d.MerchandiseOut,
                IntKuwei = null,
                MerchandiseNumber = d.MerchandiseNumber,
                InttOrderNumber = null,
                MerchandiseINPrice = d.MerchandiseINPrice,
                IntOrderPrice = null,
                Reamres = d.Reamres
            }).ToList();
            return new StockInOrderDtoWithDetails
            {
                StockInOrder = stockInOrder,
                Details = stockInOrderDetails
            };
        }

        // 3. 根据主表ID联查主表和明细
        public async Task<StockInOrderDtoWithDetails> GetWithDetailsAsync(int stockInOrderId)
        {
            var stockInOrder = await Repository.GetAsync(stockInOrderId);
            var details = await LazyServiceProvider.LazyGetRequiredService<IRepository<OrderDetailInt, int>>().GetListAsync(d => d.IntOrderId == stockInOrderId);
            var stockInOrderDto = ObjectMapper.Map<OrderStockIn, StockInOrderDto>(stockInOrder);
            var detailDtos = details.Select(d => ObjectMapper.Map<OrderDetailInt, StockInOrderDetailDto>(d)).ToList();
            return new StockInOrderDtoWithDetails
            {
                StockInOrder = stockInOrderDto,
                Details = detailDtos
            };
        }

        // 4. 根据InventoryTranId批量联查
        public async Task<List<StockInOrderDtoWithDetails>> GetAllWithDetailsByInventoryTranIdAsync(int inventoryTranId)
        {
            var stockInOrders = await Repository.GetListAsync(x => x.InventoryTranId == inventoryTranId);
            var stockInOrderIds = stockInOrders.Select(o => o.Id).ToList();
            var allDetails = await LazyServiceProvider.LazyGetRequiredService<IRepository<OrderDetailInt, int>>().GetListAsync(d => stockInOrderIds.Contains(d.IntOrderId ?? 0));
            var result = stockInOrders.Select(order =>
            {
                var dto = ObjectMapper.Map<OrderStockIn, StockInOrderDto>(order);
                var details = allDetails
                    .Where(d => d.IntOrderId == order.Id)
                    .Select(d => ObjectMapper.Map<OrderDetailInt, StockInOrderDetailDto>(d))
                    .ToList();
                return new StockInOrderDtoWithDetails
                {
                    StockInOrder = dto,
                    Details = details
                };
            }).ToList();
            return result;
        }
    }
} 